import { defineStore } from 'pinia'
import Api from '@/api'
import i18n from '@/i18n'

export const useLangStore = defineStore('lang', {
  state: () => {
    return {
      'zh-cn': {},
      'en-us': {},
      'titleObj': {} as any,
    }
  },

  actions: {
    // 下载语言
    async downloadLanguage() {
      // 默认语言
      const sessionHeaders = sessionStorage.getItem('headers')
      const langKey =
        sessionHeaders &&
        JSON.parse(sessionHeaders) &&
        JSON.parse(sessionHeaders).language_id
          ? JSON.parse(sessionHeaders).language_id
          : 'zh-cn'

      let localVersion = '' // 当前语言的版本号
      const localLang = this[langKey]
      if (localLang && localLang.sources && localLang.version) {
        // 获取到当前语言的版本号
        localVersion = localLang?.version
      }

      await Api.getLanguageEntries(langKey, localVersion)
        .then((res: any) => {
          const responseVersion = res?.data?.version
          // 如果一样的话,或者没返回内容,则代表一样
          if (
            (localVersion && localVersion == responseVersion) ||
            res?.data == null
          ) {
            i18n.global.mergeLocaleMessage(langKey, this[langKey].sources)
          }else{
            i18n.global.mergeLocaleMessage(langKey, res?.data?.sources || {})
            this[langKey] = res?.data
          }
        })
        .catch((err: any) => {

        })
    },
    // 下载标题
    async downloadTitle() {
      await Api.getLanguageTitle()
        .then((res: any) => {
          if(res.code == 0){
            this.titleObj = res?.data || {}
          }
        })
        .catch((err: any) => {
          console.log(err)
        })
    }
  },
  persist: {
    enabled: true,
    strategies: [
      {
        storage: localStorage, //自定义存储位置
      },
    ],
  },
})
